import 'package:demo/model/entity/home_recommend_entity.dart';
import 'package:demo/model/repository/home_repository.dart';
import 'package:demo/widget/custom_image.dart';
import 'package:demo/widget/pull_refresh.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class RefreshList extends StatefulWidget {
  const RefreshList({Key? key}) : super(key: key);

  @override
  _RefreshListState createState() => _RefreshListState();
}

class _RefreshListState extends State<RefreshList> {
  List<LinkData> items = [];
  late final RefreshController _refreshController;

  /// 分页的计数器
  int _pageNum = 1;

  /// 要求返回的是否成功，会自动对应refresh success 和 failed
  Future<ActionStatus> _onRefresh() async {
    final List<LinkData>? entity = await HomeRepository.getRecommendLayout(30, _pageNum);
    if (entity != null) {
      setState(() {
        _pageNum = 1;
        items = entity;
      });
    }
    return ActionStatus.Success;
  }

  /// 下拉加载更多
  Future<ActionStatus> _onLoading() async {
    await Future.delayed(Duration(milliseconds: 1000));
    final List<LinkData>? entity = await HomeRepository.getRecommendLayout(30, _pageNum + 1);
    if (entity != null) {
      setState(() {
        _pageNum++;
        items.addAll(entity);
      });
      return ActionStatus.Success;
    } else {
      return ActionStatus.Failed;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("刷新列表"),
      ),
      body: PullRefresh(
        enablePullRefresh: true,
        enableLoadMore: true,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        initialRefresh: true,
        onControllerCreateCallback: (controller) {
          _refreshController = controller;
        },
        child: ListView.builder(
          itemBuilder: (c, i) {
            return Card(
              child: CustomImage.networkOrDisk(
                items[i].thumbnailUrl!,
                fit: BoxFit.cover,
                imagePathKey: '',
              ),
            );
          },
          itemExtent: 135.0,
          itemCount: items.length,
        ),
      ),
    );
  }
}
